﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace AcctrueWMS.Foundation.Data
{
    public class SequenceNoGenerator
    {
        public IDataModelContext Context
        {
            get;
            set;
        }

        public string Generate(string expr, string tableName, string columnName, IDataModelContext context)
        {
            StringBuilder sb = new StringBuilder();
            Regex reg = new Regex("(?<lexture>((?!{).)+)?({(?<expr>.*?)})*");

            if (!reg.IsMatch(expr))
                return string.Empty;

            else
            {
                Match m = reg.Match(expr);
                string sn = m.Groups["lexture"] != null ? m.Groups["lexture"].Value : string.Empty;

                foreach (Capture c in m.Groups["expr"].Captures)
                {
                    string[] stem = c.Value.Split(',');
                    
                    switch(stem[0].Trim())
                    {
                        //时间类型
                        case "1":
                            sn+=DateTime.Now.ToString(stem[1]);
                            break;
                        //流水号类型
                        case "2":
                            sn+=context.GetSequenceNo(tableName, columnName).ToString().PadLeft(int.Parse(stem[1]),'0');
                            break;
                        //与时间相关的流水号类型
                        case "3":
                            sn += context.GetSequenceNo(tableName,columnName+DateTime.Now.ToString(stem[2])).ToString().PadLeft(int.Parse(stem[1]),'0');
                            break;
                    }
                }
                return sn;
            }            
        }
    }
}
